import { Button, InputItem, List, TextareaItem, Toast, WhiteSpace, WingBlank, Calendar } from "antd-mobile";
import { addon } from "pao-aop";
import { BaseReactElement, BaseReactElementControl, BaseReactElementState, reactControl } from "pao-aop-client";
import React from "react";
import { request, setMainFormTitle } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { IntelligentElderlyCareAppStorage } from "src/projects/app/appStorage";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import { CharitableResult } from "../result";
import { SocietyInformation } from "../society-information";
import zhCN from 'antd-mobile/lib/calendar/locale/zh_CN';
/**
 * 组件：冠名基金状态
 */
export interface CharitableTitleFundViewState extends BaseReactElementState {
    // 捐款人名义
    donate_name?: string;
    // 基金金额
    donate_money?: number;
    // 联系方式
    contacts?: string;
    // 救助对象
    donate_object?: string;
    // 捐款意向
    donate_intention?: string;
    // 捐款留言
    remark?: string;
    // 防止重复发送
    isSend?: boolean;
    // 慈善会信息
    society_info?: any;
    // 是否展示结果页面
    isResult?: boolean;
    // 日历选择
    show?: any;
    config?: any;
    // 开始时间
    begin_date?: any;
    // 结束时间
    end_date?: any;
}

const now = new Date();
/**
 * 组件：冠名基金
 * 冠名基金
 */
export class CharitableTitleFundView extends BaseReactElement<CharitableTitleFundViewControl, CharitableTitleFundViewState> {
    originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;
    constructor(props: any) {
        super(props);
        this.state = {
            donate_name: '',
            donate_money: 0,
            contacts: '',
            remark: '',
            donate_intention: '',
            isSend: false,
            society_info: [],
            isResult: false,
            show: false,
            config: '',
            begin_date: '',
            end_date: '',
        };
    }
    componentDidMount() {
        let user = IntelligentElderlyCareAppStorage.getCurrentUser();
        if (!user) {
            this.props.history!.push(ROUTE_PATH.login);
            return;
        }
        // 获取慈善会信息
        request(this, AppServiceUtility.charitable_service.get_charitable_society_list!({}, 1, 1))
            .then((data: any) => {
                if (data.result && data.result[0]) {
                    this.setState({
                        society_info: data.result[0] || [],
                    });
                }
            })
            .catch(error => {
                Toast.fail(error.message);
            });
    }
    changeValue = (e: any, inputName: any) => {
        this.setState({
            [inputName]: e
        });
    }
    CharitableTitleFund = (): boolean => {
        let { donate_name, donate_object, begin_date, end_date, donate_money, donate_intention, contacts, remark } = this.state;
        if (!donate_name) {
            Toast.fail('请输入基金名字', 1);
            return false;
        }
        if (!donate_money) {
            Toast.fail('请输入基金金额', 1);
            return false;
        }
        if (isNaN(Number(donate_money))) {
            Toast.fail('请输入正确的基金金额', 1);
            return false;
        }
        if (Number(donate_money) < 500000) {
            Toast.fail('基金金额必须大于￥500000', 1);
            return false;
        }
        if (!donate_intention) {
            Toast.fail('请输入基金意向', 1);
            return false;
        }
        if (!donate_object) {
            Toast.fail('请输入救助对象', 1);
            return false;
        }
        if (!contacts) {
            Toast.fail('请输入联系方式', 1);
            return false;
        }
        if (begin_date === '') {
            Toast.fail('请选择开始时间！', 1);
            return false;
        }
        if (end_date === '') {
            Toast.fail('请选择结束时间！', 1);
            return false;
        }
        if (!remark) {
            Toast.fail('请输入基金描述', 1);
            return false;
        }
        Toast.loading('Loading...', 3, () => {
            console.log('Load complete !!!');
        });

        var param: any = {
            // donate_project_id: this.state.donate_project_id,
            donate_name,
            donate_money: Number(donate_money),
            donate_intention,
            donate_object,
            remark: remark,
            contacts: contacts,
            begin_date: begin_date,
            end_date: end_date,
            // 基金捐赠标识
            donate_type: '基金',
        };
        Toast.loading('Loading...', 11, () => {
        });
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('提交失败，请稍候再试', 3);
            },
            10000
        );
        request(this, AppServiceUtility.charitable_service.update_charitable_title_fund!(param))
            .then((datas: any) => {
                if (datas === 'Success') {
                    clearTimeout(st);
                    Toast.hide();
                    this.setState({
                        isResult: true,
                    });
                } else {
                    Toast.fail('提交失败，请稍候再试', 3);
                }
            }).catch((error: Error) => {
                Toast.fail(error.message);
            });
        return false;
    }
    onConfirm = (begin_date: any, end_date: any) => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            show: false,
            begin_date,
            end_date,
        });
    }

    onCancel = () => {
        document.getElementsByTagName('body')[0].style.overflowY = this.originbodyScrollY;
        this.setState({
            show: false,
            begin_date: undefined,
            end_date: undefined,
        });
    }
    renderBtn(zh: any, en: any, config: any = {}) {
        config.locale = zhCN;
        return (
            <List.Item
                arrow="horizontal"
                onClick={() => {
                    document.getElementsByTagName('body')[0].style.overflowY = 'hidden';
                    this.setState({
                        show: true,
                        config,
                    });
                }}
            >
                {zh}
            </List.Item>
        );
    }
    render() {
        setMainFormTitle("申请冠名基金");
        if (this.state.isResult === true) {
            return (
                <CharitableResult pprops={this.props} status="wait" title="提交成功，请等待审批" return_url={ROUTE_PATH.charitableTitleFundRecord} />
            );
        }
        const { society_info, begin_date, end_date } = this.state;
        return (
            <div>
                <List renderHeader={() => '基金名字'}>
                    <InputItem clear={true} placeholder="捐款人/企业" onChange={(e) => this.changeValue(e, 'donate_name')} />
                </List>
                <List renderHeader={() => '基金金额'}>
                    <InputItem placeholder="请输入基金金额" onChange={(e) => this.changeValue(e, 'donate_money')} />
                </List>
                <List renderHeader={() => '基金意向'}>
                    <InputItem placeholder="请输入捐款意向" onChange={(e) => this.changeValue(e, 'donate_intention')} />
                </List>
                <List renderHeader={() => '救助对象'}>
                    <InputItem placeholder="请输入救助对象" onChange={(e) => this.changeValue(e, 'donate_object')} />
                </List>
                <List renderHeader={() => '联系方式'}>
                    <InputItem placeholder="请输入联系方式" onChange={(e) => this.changeValue(e, 'contacts')} />
                </List>
                <List
                    renderHeader={() => {
                        if (begin_date && end_date) {
                            return begin_date.toLocaleString() + '-' + end_date.toLocaleString();
                        } else if (begin_date && end_date) {
                            return begin_date.toLocaleString() + '-' + end_date.toLocaleString();
                        }
                        return '选择基金时间';
                    }}
                >
                    {this.renderBtn('选择基金时间', '选择基金时间', {
                        pickTime: true,
                        onSelect: (date: any, state: any) => {
                            console.log('onSelect', date, state);
                            // return [date, new Date(+now - 604800000)];
                        },
                    })}
                </List>
                <List renderHeader={() => '基金描述'}>
                    <TextareaItem placeholder="请输入基金描述" rows={3} autoHeight={true} onChange={(e) => this.changeValue(e, 'remark')} />
                </List>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <WingBlank size="lg">
                    <Button type="primary" onClick={this.CharitableTitleFund}>提交申请</Button>
                </WingBlank>
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                {society_info && society_info['id'] ? <SocietyInformation data_info={society_info} /> : null}
                <WhiteSpace size="lg" />
                <WhiteSpace size="lg" />
                <Calendar
                    {...this.state.config}
                    visible={this.state.show}
                    onCancel={this.onCancel}
                    onConfirm={this.onConfirm}
                    defaultValue={begin_date && end_date ? [begin_date, end_date] : null}
                    defaultDate={now}
                    minDate={new Date(+now - 5184000000)}
                    maxDate={new Date(+now + 31536000000)}
                />
            </div>
        );
    }
}

/**
 * 控件：冠名基金控制器
 * 冠名基金
 */
@addon('CharitableTitleFundView', '冠名基金', '冠名基金')
@reactControl(CharitableTitleFundView, true)
export class CharitableTitleFundViewControl extends BaseReactElementControl {

}